package com.jlju.djmhadmin.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jlju.djmhadmin.common.GenericResponse;
import com.jlju.djmhadmin.common.util.*;
import com.jlju.djmhadmin.dao.common.util.DataEncryptUtil;
import com.jlju.djmhadmin.dao.entity.User;
import com.jlju.djmhadmin.dao.service.UserService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.concurrent.Callable;

/** 
* @Description: 登陆用户管理 
* @Param:  
* @return:  
* @Author: LiTing [li_ting1@suixingpay.com] 
* @Date: 2018/4/27 
* @Time: 下午4:57
*/ 
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserService userService;


    /**
    * @Description: 用户登陆操作
    * @Param:  json
    * @return:  Callable<GenericResponse<String>>
    * @Author: LiTing [li_ting1@suixingpay.com]
    * @Date: 2018/4/27
    * @Time: 下午5:12
    */
    @Validations(requiredStrings={
            @RequiredStringValidator(fieldName="acNo",errCode="ACM0020",errMsg="请求参数不足,账号不能为空"),
            @RequiredStringValidator(fieldName="password",errCode="ACM0021",errMsg="请求参数不足，密码不能为空")
    })
    @RequestMapping(value = "/login")
    public Callable<GenericResponse<String>> login(@RequestBody String json, HttpSession session) {
        try {
            logger.info("登陆开始，入参：" + json);
            User user = JsonUtil.jsonToObject(json, User.class);
            User finUser = JsonUtil.jsonToObject(json, User.class);
            user = this.userService.login(user.getAcNo(), user.getPassword());
            if(StringUtils.isEmpty(user)) {
                finUser.setPassword(DataEncryptUtil.encryptBASE64(finUser.getPassword().getBytes()));
                user = this.userService.login(finUser.getAcNo(), finUser.getPassword());
            }
            if (!StringUtils.isEmpty(user)) {
                User finalUser = user;
                //记录当前登陆对象
                session.setAttribute("login_user", finalUser.getAcNo());
                session.setAttribute("type", finalUser.getIdentity());
                return () -> GenericResponse.success("ACM0000", "登陆信息验证成功", finalUser);
            } else {
                return () -> GenericResponse.failed("ACM0002", "用户名或密码错误");
            }
        } catch (Exception e) {
            return () -> GenericResponse.failed("ACM0003", "登陆异常,用户名或密码错误");
        }
    }

    /**
     * @Description: 用户忘记密码，并重置密码
     * @Param: account
     * @return:
     * @Author: LiTing [liting08011@163.com]
     * @Date: 2018/4/23
     * @Time: 下午4:57
     */
    @RequiredStringValidator(fieldName = "acNo", trim = true, errCode = "ACM0020", errMsg = "请求参数不足,账号不能为空")
    @RequestMapping(value = "/forget")
    public Callable<GenericResponse<String>> forget(@RequestBody String account) {
        logger.info("用户密码重置开始，入参 ： " + account);
        String acNo = StringUtils.trimFirstAndLastChar(account,'\"');
        if (StringUtils.isNullOrEmpty(acNo)) {
            return () -> GenericResponse.failed("ACM0005", "密码重置异常,请输入账号");
        } else {
            try {
                //查询现在用户状态
                if(StringUtils.isEmpty(this.userService.findOneById(acNo))) {
                    throw new Exception("用户信息不存在");
                }
                this.userService.forget(acNo);
                logger.info("密码重置成功" + acNo);
                return () -> GenericResponse.success("ACM0004", "密码已重置，请查看邮箱", acNo);
            } catch (Exception e) {
                logger.error("密码重置失败" + e);
                return () -> GenericResponse.failed("ACM0005", "密码重置异常");
            }
        }
    }

    @ApiOperation("注销用户")
    @RequestMapping(value = "/delete")
    @RequiredStringValidator(fieldName = "acNo", trim = true, errCode = "ACM0020", errMsg = "请求参数不足,账号不能为空")
    public Callable<GenericResponse<String>> delete(@RequestBody String json) {
        logger.info("***用户注销开始*** 入参： " + json);
        try {
            User user = JsonUtil.jsonToObject(json, User.class);
            this.userService.deleteById(user);
            logger.info("***用户信息注销成功***");
//            this.userService.postMail(student.getEmail(), "学籍注销成功， 学号： " + student.getAcNo() + "姓名 ：" + student.getName());
            return () -> GenericResponse.success("ACM0006", "注销成功", user);
        } catch (Exception e) {
            logger.error("***用户信息注销失败***" + e);
            return () -> GenericResponse.failed("ACM0007", "注销失败");
        }
    }

    @ApiOperation("新增登陆用户")
    @RequestMapping(value = "/add")
    public Callable<GenericResponse<String>> add(@RequestBody String json) {
        logger.info("***新增用户开始***入参：" + json);
        try {
            User user = JsonUtil.jsonToObject(json, User.class);
            if(!ValidatorUtil.isEmail(user.getEmail())) {
                throw new Exception("邮箱格式不准确");
            }
            if(!ValidatorUtil.isMobile(user.getPhone())){
                throw new Exception("手机号格式不准确");
            }
            //加密
            user.setPassword(DataEncryptUtil.encryptBASE64(user.getPassword().getBytes()));
            this.userService.add(user);
            logger.info("***新增用户成功***");
            return () -> GenericResponse.success("ACM0008", "添加成功", user);
        } catch (Exception e) {
            logger.error("***新增用户失败***" + e);
            return () -> GenericResponse.failed("ACM0009", "添加失败");
        }
    }

    @ApiOperation("查看用户详细信息")
    @RequestMapping(value = "/findOneById")
    public Callable<GenericResponse<String>> findOneById(@RequestBody String json) {
        logger.info("***学生学籍详细查询开始***");
        try {
            User student = JsonUtil.jsonToObject(json, User.class);
            this.userService.findOneById(student.getAcNo());
            logger.info("***查看用户详细信息查询成功***");
            return () -> GenericResponse.success("ACM0012", "详细查询成功", student);
        } catch (Exception e) {
            logger.error("***查看用户详细信息查询失败***" + e);
            return () -> GenericResponse.failed("ACM0013", "查询详情失败");
        }
    }

    @ApiOperation("查看全部用户，带分页")
    @RequestMapping(value = "/findAll")
    public Callable<GenericResponse<User>> findAll(@RequestBody String json, int pageNum, int pageSize) {
        logger.info("***用户列表查询开始*** , 入参 ： " + json);
        try {
            User user = JsonUtil.jsonToObject(json, User.class);
            PageHelper.startPage(pageNum, pageSize);
            List<User> list = this.userService.findAll(user);
            // 用PageInfo对结果进行包装
            PageInfo pageInfo = new PageInfo(list);
            logger.info("***查看全部用户信息信息（分页） 成功***" + pageInfo);
            return () -> GenericResponse.success("ACM0010", "查询成功", pageInfo);
        } catch (Exception e) {
            logger.error("***查看全部用户信息信息（分页）失败***" + e);
            return () -> GenericResponse.failed("ACM0011", "查询失败");
        }
    }

    @ApiOperation("用户信息更新")
    @RequestMapping(value = "/updateById")
    @RequiredStringValidator(fieldName="cardId",trim=true,errCode="ACM9900",errMsg="请求参数不足,身份证号不能为空")
    public Callable<GenericResponse<String>> updateById(@RequestBody String json) {
        logger.info("***用户信息更新开始***入参：" + json);
        User student = JsonUtil.jsonToObject(json,User.class);
        try {
            try {
                this.userService.updateById(student);
            } catch (Exception e) {
                logger.error("***用户信息更新失败***");
                throw new Exception("生信息更新失败");
            }
            logger.info("***用户信息更新成功***");
            return () -> GenericResponse.success("ACM0014", "更新成功", student);
        } catch (Exception e) {
            logger.error("***用户信息更新失败***" + e);
            return () -> GenericResponse.failed("ACM0015", "更新失败");
        }
    }

    @ApiOperation("测试类")
    @RequestMapping(value = "/test")
    public String test () {
        System.out.println("aaaaaaa");
        return "aaa";
//        if(!ValidatorUtil.isMobile(email)) {
//                logger.error("出错！");
//        } else {
//            logger.info("成功");
//        }
    }

    @RequestMapping("/hello")
    public String hello(@RequestParam String name) {
        System.out.println("aaaaaaa");
        return "hello "+name+"，this is first messge";
    }
}